package com.gaohe.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gaohe.common.R;
import com.gaohe.pojo.Orders;
import com.gaohe.service.OrdersService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/orders")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */

    @GetMapping("/page")
    public R page(@RequestParam Integer page,
                  @RequestParam Integer pageSize,
                  @RequestParam(required = false) Integer status) {
        // service
        PageInfo<Orders> ordersPageInfo = ordersService.getAll(page, pageSize, status);
        return R.success(ordersPageInfo);
    }

    /**
     * 新增订单
     *
     * @param orders
     * @return
     */
    @PostMapping("/placeOrder")
    public R placeOrder(@RequestBody Orders orders) {
        return ordersService.placeOrder(orders) ? R.success(orders.getShopId()) : R.error("下单失败");
    }

    /**
     * 根据 用户 id 商品名称 查询订单
     * @param userId
     * @param shopName
     * @return
     */
    @GetMapping
    public R getOrdersByUserId(@RequestParam Long userId,
                               @RequestParam(required = false) String shopName) {
        //List<Orders> ordersList = ordersService.getOrdersByUserId(userId,shopName);
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.eq(Orders::getUserId,userId);
        qw.like(ObjectUtils.isNotEmpty(shopName),Orders::getShopName,shopName);
        List<Orders> ordersList = ordersService.list(qw);
        return R.success(ordersList);
    }

    /**
     * 删除订单
     * @param id
     * @return
     */
    @DeleteMapping
    public R deleteById(@RequestParam Long id){
        boolean flag = ordersService.deleteById(id);
        return flag ? R.success("删除成功"):R.error("删除失败");
    }

}
